/*
 * dateAnalysis.js
 * 时序分析
 */
;
(function (call) {
    var main = {
        baseUrl: CafeJS.CXT,
        datepicker: null,
        dataSource: [
            { "name": "自动站", "modelId": "ZDZ","color": "#fe5150"},
            { "name": "EC", "modelId": "ECMF" ,"color": "#1ca1e2"},
            { "name": "ED", "modelId": "ED" ,"color": "#595fd6"},
            { "name": "TJWRF", "modelId": "TJWRF" ,"color": "#f881f2"},
            //{ "name": "国家指导", "modelId": "NWGD" ,"color": "#00d4bb"},
            { "name": "CMA_GFS", "modelId": "GRAPES" ,"color": "#566f86"},
            { "name": "CMA_MESO", "modelId": "GRAPES-MESO" ,"color": "#eaa773"}
        ],
        elementArr: {
            "10min": [
                { "name": "2m温度", "elementId": "T", "color": "#fe5150", "forecastId": "tmp" },
                { "name": "降水量", "elementId": "RAIN", "color": "#1ca1e2", "forecastId": "tp" },
                { "name": "10m风", "elementId": "WS_10M,WD_10M", "color": "#595fd6", "forecastId": "eda10m" },     //风速，风向
                { "name": "相对湿度", "elementId": "RH", "color": "#00d4bb", "forecastId": "rh" },
                //{ "name": "能见度", "elementId": "VIS_10M", "color": "#566f86", "forecastId": "vis" }
            ],
            "1h": [
                { "name": "6h阵风", "elementId": "", "color": "#f881f2", "forecastId": "ws6h" },
                { "name": "海平面气压", "elementId": "ybEle", "color": "#eaa773", "forecastId": "prmsl" },
                { "name": "总云量", "elementId": "ybEle", "color": "rgb(0,150,136)", "forecastId": "tcc" },
                { "name": "850hpa温度", "elementId": "ybEle", "color": "rgb(49,173,204)", "forecastId": "tmp850hpa" },
                { "name": "700hpa湿度", "elementId": "ybEle", "color": "rgb(254,68,199)", "forecastId": "rh700hpa" },
                { "name": "850hpa湿度", "elementId": "ybEle", "color": "rgb(79,183,58)", "forecastId": "rh850hpa" }
            ]
        },
        currentTime: "",
        dataSourceNames: [],
        dataSourceIds: [],
        elementIds: [],
        elementForecastIds: [],
        elementHeights: [],
        colors: [],
        elementNames: [],
        endTime: "",
        startTime: "",
        currentModel: "单要素",
        echartOption: {},
        echartObj: Object,
        stationKey: '',
        isByDateLength: false,
        router: {
            getSiterData: '/zhfx/station/queryHourYbStation',
            getSkEchartData: '/zhfx/station/list/queryChartData',
            getYbEchartDate: '/gridtools/NetCDFParse2Grid/readData4Chart'
        },
        init: function () {
            var that = this;
            that.currentTime = window.analysis.currentTime;
            if (window.analysis.type === "1h") {                        //通过预报分析，时序图
                that.currentTime = that.initYuBaoDate(that.currentTime);
                that.initDatePicker(12, 'yyyy-MM-dd hh', 'H', [8, 20]);
            } else {
                that.initDatePicker(1, 'yyyy-MM-dd hh', 'H', []);
            }
            that.echartOption = that.getEchartOption();
            that.initView();
        },
        //预报第一次见来，通过开始时间算起报时间,如果是国家指导
        initYuBaoDate: function (currentTime) {
            var date = new Date(currentTime);
            var hour = date.getHours();
            if (hour <= 4) {
                date.setDate(date.getDate() - 1);
                date.setHours(8);
            } else if (hour >= 5 && hour <= 15) {
                date.setDate(date.getDate() - 1);
                date.setHours(20);
            } else if (hour >= 16 && hour <= 23) {
                date.setHours(08);
            }
            return new Date(date).format("yyyy-MM-dd hh:00:00");
        },
        initView: function () {
            var that = this;
            that.echartObj = echarts.init(document.getElementById("analysisEchart"));
            that.echartObj.clear();

            that.getSiteData();
        },
        // 初始化时间控件
        initDatePicker: function (timeInterval, dateFmt, dateType, customHm) {
            var that = this;
            that.datepicker = CafeJS.Datepicker({
                appendTo: "#datepicker-dateAnalysis",
                type: 3,
                curDate: that.currentTime,
                dateFmt: dateFmt,
                dateType: dateType,
                timeInterval: timeInterval,
                customHm: customHm,
                call: function (val) {
                    that.getData(false);
                }
            });
        },
        //获取常规站点集合
        getSiteData: function () {
            var that = this;
            var parentObj = $(".sites");
            parentObj.html("");
            $.ajax({
                url: that.router.getSiterData,
                data: {
                    "stationType": 2
                },
                type: "GET",
                dataType: 'json',
                success: function (res) {
                    for (var i = 0; i < res.data.length; i++) {
                        var obj = $("<div class='analysisBtn' name='" + res.data[i].stationId + "' lon='" + res.data[i].lon + "' lat='" + res.data[i].lat + "'>" + res.data[i].stationName + "</div>");
                        parentObj.append(obj);
                        obj.unbind("click").bind("click", function () {
                            $(this).addClass("active").siblings().removeClass("active");
                            that.getData(false);
                        });
                    }
                    var stationId = window.analysis.stationId;
                    if (stationId) {
                        $(".sites .analysisBtn[name=" + stationId + "]").addClass("active").siblings().removeClass("active");
                    }
                    if(!window.analysis.stationLon){
                       $(".sites .analysisBtn").eq(1).addClass("active").siblings().removeClass("active");
                    }
                    //设置自定义
                    // var selfObj = $("<div class='analysisBtn'>自定义</div>");
                    // parentObj.append(selfObj);
                    // selfObj.unbind("click").bind("click", function () {
                    //     alert("自定义");
                    // })
                    that.bindEvt();
                }
            })

        },
        //根据时间，获取元素选择
        setElements: function (type) {
            //点击要素选择
            var that = this;
            var elementsObj = $(".elements");
            elementsObj.html("");
            var data = that.elementArr[type];
            if(type === "1h"){
                data = that.elementArr["10min"].concat(data);
            }
            for (var i = 0; i < data.length; i++) {
                obj1 = $("<div class='analysisBtn' name='" + data[i].elementId + "' color='" + data[i].color + "' forecastId='" + data[i].forecastId + "'>" + data[i].name + "</div>");
                obj1.data("ele", data[i]);
                obj1.addClass("element");
                elementsObj.append(obj1);
                if (i === 0) {
                    obj1.addClass("active");
                }
                obj1.unbind("click").bind("click", function () {
                    that.checkIsSelectMore($(this), "elements");
                })
            }
        },
        //初始化数据源
        bindEvt: function () {
            var that = this;
            //时间间隔切换
            $(".dateType >div").each(function () {
                $(this).unbind("click").bind("click", function () {
					if ($(this).hasClass('active')) return;
                    $(this).addClass("active").siblings().removeClass("active");
                    if ($(this).text() === "分钟") {
                        that.setElements("10min");
                        that.initDatePicker(1, 'yyyy-MM-dd hh', 'H', []);
                        $(".dataSource >div").addClass("notEvent");
                        $(".dataSource >div[id='ZDZ']").addClass("active").removeClass("notEvent").siblings().removeClass("active");
                    } else {
                        that.setElements("1h");
                        that.initDatePicker(12, 'yyyy-MM-dd hh', 'H', [8, 20]);
                        $(".dataSource >div").removeClass("notEvent");
                        $(".dataSource >div[id='ECMF']").addClass("active").siblings().removeClass("active");
                        if ($(".modelTabs .modelTabActive").text() === "单要素") {
                            $(".dataSource >div[id='ZDZ']").addClass("active");
                        }
                    }
                    that.getData(false);
                })
            })
            //点击数据源
            var dataSourceObj = $(".dataSource");
            dataSourceObj.html("");
            for (var i = 0; i < that.dataSource.length; i++) {
                var obj = $("<div class='analysisBtn' color='" + that.dataSource[i].color + "'  id='" + that.dataSource[i].modelId + "'>" + that.dataSource[i].name + "</div>");
                dataSourceObj.append(obj);
                obj.unbind("click").bind("click", function () {
                    that.checkIsSelectMore($(this), "dataSource");
                })
            }
            //切换单模式，多模式，单模式单要素
            $(".modelTabs .modelTab").each(function () {
                $(this).unbind("click").bind("click", function () {
                    that.currentModel = $(this).text();
                    $(this).addClass("modelTabActive").siblings().removeClass("modelTabActive");
                    if (that.currentModel === "单要素") {
                        $(".elements div").eq(0).addClass("active").siblings().removeClass("active");
                    } else if (that.currentModel === "多要素") {
                        var dateType = $(".dateType .active").text();
                        if (dateType === "分钟") {
                            $(".dataSource >div[id='ZDZ']").addClass("active").siblings().removeClass("active");
                        } else if (dateType === "小时") {
                            $(".dataSource >div[id='ECMF']").addClass("active").siblings().removeClass("active");
                        }
                    }
                    that.getData(false);
                })
            })
            //默认选择，点击
            if (window.analysis.type === "10min") {
                $(".dateType >div").eq(0).click();
                $(".ybDateLength").hide();
                that.isByDateLength = false;
            } else if (window.analysis.type === "1h") {
                $(".dataSource #ZDZ").addClass("notEvent").removeClass("active").siblings().addClass("active").removeClass("notEvent");
                $(".dateType >div").eq(0).addClass("notEvent");
                $(".dateType >div").eq(1).addClass("active");
                this.setElements("1h");
                that.getData(false);
                $(".ybDateLength").show();
                //绑定切换预报时间长度
                that.isByDateLength = true;
                $(".ybDateLengths .ybDateLength").unbind("click").bind("click",function(){
                    $(this).addClass("ybDateLengthActive").siblings().removeClass("ybDateLengthActive");
                    that.getData();
                })
            }
        },
        //点击数据源，获取数据
        getData: function () {
            var that = this;
            that.dataSourceNames = [];
            that.dataSourceIds = [];
            that.elementIds = [];
            that.colors = [];
            that.elementNames = [];
            that.elementHeights = [];
            that.elementForecastIds = [];
            var requestModel = [];
            var colorArr1 = [];
            var colorArr2 = [];
            $(".dataSource .active").each(function () {
                that.dataSourceNames.push($(this).text());
                if ($(this).attr("id") !== "ZDZ") {
                    requestModel.push($(this).attr("id"))
                }
                that.dataSourceIds.push($(this).attr("id"));
                colorArr1.push($(this).attr("color"));
            })
            $(".elements .element.active").each(function () {
                that.elementIds.push($(this).attr("name"));
                colorArr2.push($(this).attr("color"));
                that.elementNames.push($(this).text());
                that.elementHeights.push($(this).attr("height"));
                that.elementForecastIds.push($(this).attr("forecastId"))
            })
            if(that.currentModel === "单要素"){
                that.colors = colorArr1;
            }else{
                that.colors = colorArr2;
            }

            if (that.elementIds.length === 0 || that.dataSourceNames.length === 0) {
                that.echartObj.clear();
                return;
            }
            var currentTime = that.datepicker.getVal();     //这个时间点为当前时间，分隔时间点
            var station = that.getStationIdName();
            if (that.dataSourceNames.length === 1 && that.dataSourceNames[0] === "自动站") {               //数据源只有自动站
                that.endTime = currentTime + ":00";
                var time = new Date(that.endTime);
                time = time.setDate(time.getDate() - 1);
                time = new Date(time);
                that.startTime = time.format("yyyy-MM-dd hh:mm:ss");
                var mins = $(".dateType .active").attr("name");
                that.startTime = new Date(new Date(that.startTime).setHours(time.getHours() + 1)).format("yyyy-MM-dd hh:mm:ss");;
 
                var param = {
                    stationId: station.stationId,
                    mins: mins,
                    startTime: that.startTime,
                    endTime: that.endTime
                }
                that.multipleRequest([that.router.getSkEchartData], [param], true);
            } else if (that.dataSourceNames.length >= 1 && that.dataSourceNames.indexOf("自动站") === -1) {       //数据源没有自动站，都是预报
                var endPeriod = 96;
                var intervalPeriod = 3;
                if(that.isByDateLength){
                    endPeriod = Number($(".ybDateLengths .ybDateLengthActive").text());
                    intervalPeriod = Number($(".ybDateLengths .ybDateLengthActive").attr("interval"));
                }
                that.startTime = currentTime + ":00";
                var time = new Date(that.startTime);
                time = time.setDate(time.getDate() + endPeriod/24);
                time = new Date(time);
                that.endTime = time.format("yyyy-MM-dd hh:mm:ss");
                that.startTime = new Date(new Date(that.startTime).setHours(time.getHours() + intervalPeriod)).format("yyyy-MM-dd hh:mm:ss");;
                //that.setEchartTitle(station.stationName, that.startTime, that.endTime);
                var param = {
                    modeType: requestModel.join(","),
                    qbTime: new Date(currentTime + ":00").format("yyyyMMddhhmmss"),
                    //qbTime: "20191108080000",
                    elements: that.elementForecastIds.join(","),
                    stationIDs: station.stationLonLat,
                    startPeriod: 0,
                    endPeriod: endPeriod,
                    inteval: intervalPeriod
                }
                that.multipleRequest([that.router.getYbEchartDate], [param], false);
            } else if (that.dataSourceNames.length > 1 && that.dataSourceNames.indexOf("自动站") > -1) {       //数据源既自动站，也预报
                var time = new Date(currentTime + ":00");
                that.startTime = time.setDate(time.getDate() - 1);
                that.startTime = new Date(that.startTime);
                that.startTime = that.startTime.format("yyyy-MM-dd hh:mm:ss");
                that.endTime = time.setDate(time.getDate() + 5);
                that.endTime = new Date(that.endTime);
                that.endTime = that.endTime.format("yyyy-MM-dd hh:mm:ss");
                var mins = $(".dateType .active").attr("name");
                var station = that.getStationIdName();
                that.startTime = new Date(new Date(that.startTime).setHours(time.getHours() + 1)).format("yyyy-MM-dd hh:mm:ss");;
                //that.setEchartTitle(station.stationName, that.startTime, that.endTime);
                var param = {
                    stationId: station.stationId,
                    mins: mins,
                    startTime: that.startTime,
                    endTime: that.endTime
                };
                var param1 = {
                    modeType: requestModel.join(","),
                    qbTime: new Date(currentTime + ":00").format("yyyyMMddhhmmss"),
                    //qbTime: "20191108080000",
                    elements: that.elementForecastIds.join(","),
                    stationIDs: station.stationLonLat,
                    strAging: 0,
                    endAging: 96,
                    inteval: 1
                }
                that.multipleRequest([that.router.getSkEchartData, that.router.getYbEchartDate], [param, param1], true);

            }
        },

        /********设置echart**********/
        drawEchart: function (skData, ybData) {
            var that = this;
            that.echartOption = that.getEchartOption();
            var isselectSk = false;
            var station = that.getStationIdName();
            that.setEchartTitle(station.stationName, that.startTime, that.endTime);
            var yAxixPosition = that.setYAxisPosition(that.elementIds);
            that.setEchartDataZoom();
            let offsetLeft = yAxixPosition.offsetLeft;
            let offsetRight = yAxixPosition.offsetRight;
            var yAxis = that.getYAxisObj();
            var series = [];
            var yAxisArr = [];
            let flag = false;
            if (that.currentModel === "单要素") {
                that.echartOption.color = that.colors;
                offsetLeft = offsetLeft - 70;
                yAxis["offset"] = offsetLeft;
                yAxis["position"] = "left";
                yAxis["name"] = that.elementNames[0] + " " + that.getUnitbyElement(that.elementNames[0]);
                var singleSkEleId = that.elementIds[0];
                var singleYbEleId = that.elementForecastIds[0];
                var dataArr = [];
                var xData = [];
                for (var i = 0; i < that.dataSourceIds.length; i++) {
                    var data = [];
                    var data1 = []
                    if (that.dataSourceNames[i] === "自动站") {
                        isselectSk = true;
                        skData.forEach(function (item) {
                            if (singleSkEleId.indexOf("WS") > -1) {
                                data1.push(item[singleSkEleId.split(",")[0]]);
                                data.push({ value: item[singleSkEleId.split(",")[0]], valueWd: item[singleSkEleId.split(",")[1]] });
                            } else {
                                data.push(item[singleSkEleId]);
                            }
                        })
                        dataArr.push({ type: "sk", data: data, "name": that.dataSourceNames[i], singleXData: data1 });
                    } else {
                        ybData[that.dataSourceIds[i]].data.forEach(function (item) {
                            if (singleYbEleId === "eda10m") {
                                data1.push(item["ws10m"]);
                                data.push({ value: item["ws10m"], valueWd: item["wd10m"] });
                            } else {
                                data.push(item[singleYbEleId]);
                            }
                        })
                        var key = that.dataSourceIds[i];
                        dataArr.push({ type: key, data: data, "name": that.dataSourceNames[i], singleXData: data1 })
                    }
                }
                if (isselectSk && dataArr.length > 1) {
                    dataArr.forEach(function (item) {
                        if (item.type === "sk") {
                            item.data = that.addArrNull(item.data, true);
                        } else {
                            item.data = that.addArrNull(item.data, false);
                        }
                    })
                }
                dataArr.forEach(function (item, index) {
                    var serieObj = that.getSerieObj(that.dataSourceNames[index]);
                    serieObj.eleId = that.elementForecastIds[0];
                    if(that.elementIds[0] === "RAIN"){
                        serieObj.type = "bar";
                    }else{
                        serieObj.type = "line";
                    }
                    serieObj.data = item.data;
                    if (that.elementIds[0].indexOf("WS") > -1) {
                        serieObj = that.setSerieSymbol(serieObj);
                        xData = xData.concat(item.singleXData);
                    } else {
                        xData = xData.concat(item.data);
                    }

                    series.push(serieObj);
                })
                var newxData = []; 
                xData.filter(function(item1){
                        if(typeof item1 == "undefined"){
                            newxData.push(null);
                        }else{
                            newxData.push(item1);
                        }
                    })
                var min = that.getMinInArr(newxData).toFixed(0);
                var max = that.getMaxInArr(newxData).toFixed(0);
                if (that.elementIds[0] != 'T' && that.elementForecastIds[0] != 'tmp850hpa' && min < 0) min = 0;
                if (that.elementForecastIds[0] == 'tcc'&& max > 100 ) max = 100;
                yAxis["min"] = min;
                yAxis["max"] = max;
                yAxis["interval"] = (max - min) / 10;
                yAxisArr = [yAxis];
                that.echartOption.legend.data = that.dataSourceNames;
            }
            if (that.currentModel === "多要素") { 
                that.echartOption.color = that.colors;
                for (var i = 0; i < that.elementIds.length; i++) {
                    var serieObj = that.getSerieObj(that.elementNames[i]);
                    serieObj.eleId = that.elementForecastIds[i];
                    if(that.elementIds[i] === "RAIN"){
                        serieObj.type = "bar";
                    }else{
                        serieObj.type = "line";
                    }
                    var yAxis = that.getYAxisObj();
                    flag = !flag;
                    if (flag) {
                        offsetLeft = offsetLeft - 70;
                        yAxis["offset"] = offsetLeft;
                        yAxis["position"] = "left";
                    } else {
                        offsetRight = offsetRight - 70;
                        yAxis["offset"] = offsetRight;
                        yAxis["position"] = "right"
                    }
                    if (i !== 0) {
                        serieObj["yAxisIndex"] = i;
                    }
                    yAxis["name"] = that.elementNames[i] + " " + that.getUnitbyElement(that.elementNames[i]);
                    yAxis.axisLine.lineStyle.color = that.colors[i];
                    yAxis.axisLabel.textStyle.color = that.colors[i];
                    var dataArr = [];
                    if (that.elementIds[i].indexOf("WS") > -1) {
                        serieObj = that.setSerieSymbol(serieObj);
                    }
                    if (that.dataSourceNames[0] === "自动站") {
                        for (var j = 0; j < skData.length; j++) {
                            if (that.elementIds[i].indexOf("WS") > -1) {
                                dataArr.push(skData[j][that.elementIds[i].split(",")[0]]);
                                serieObj.data.push({ value: skData[j][that.elementIds[i].split(",")[0]], valueWd: skData[j][that.elementIds[i].split(",")[1]] });
                            } else {
                                dataArr.push(skData[j][that.elementIds[i]]);
                                serieObj.data.push(skData[j][that.elementIds[i]]);
                            }
                        }
                    } else {
                        for (var j = 0; j < ybData[that.dataSourceIds[0]].data.length; j++) {
                            if (that.elementForecastIds[i] === "eda10m") {
                                dataArr.push(ybData[that.dataSourceIds[0]].data[j]["ws10m"]);
                                serieObj.data.push({ value: ybData[that.dataSourceIds[0]].data[j]["ws10m"], valueWd: ybData[that.dataSourceIds[0]].data[j]["wd10m"] });
                            } else {
                                dataArr.push(ybData[that.dataSourceIds[0]].data[j][that.elementForecastIds[i]]);
                                serieObj.data.push(ybData[that.dataSourceIds[0]].data[j][that.elementForecastIds[i]]);
                            }
                        }
                    }
                    var newdataArr = []; 
                    dataArr.filter(function(item1){
                        if(typeof item1 == "undefined"){
                            newdataArr.push(null);
                        }else{
                            newdataArr.push(item1);
                        }
                    })
                    var min = that.getMinInArr(newdataArr).toFixed(0);
                    var max = that.getMaxInArr(newdataArr).toFixed(0);
                    if (that.elementIds[i] != 'T' && that.elementForecastIds[i] != 'tmp850hpa' && min < 0) min = 0;
                    if (that.elementForecastIds[i] == 'tcc'&& max > 100 ) max = 100;
                    if(that.elementNames[i] === "10m风"){
                        yAxis["min"] = 0;
                        yAxis["max"] = 41.5;
                        yAxis["splitNumber"] = 10;
                    }else{
                        yAxis["min"] = min;
                        yAxis["max"] = max;
                        yAxis["interval"] = (max - min) / 10;
                    }
                    yAxisArr.push(yAxis);
                    series.push(serieObj);
                }
                that.echartOption.color = that.colors;
                that.echartOption.legend.data = that.elementNames;
            }
            var newSeries = [];
            series.filter(function(item){
                var data = []
                item.data.filter(function(item1){
                    if(typeof item1 == "undefined"){
                        data.push(null);
                    }else{
                        data.push(item1);
                    }
                })
                item.data = data;
                newSeries.push(item);
            })
			debugger
            that.echartOption.series = newSeries;
            that.echartOption.yAxis = yAxisArr;
            that.echartOption.xAxis.data = that.setXAxisData(that.startTime, that.endTime);
            if(that.isByDateLength){
                that.echartOption.xAxis.axisLabel.interval = function(index,val){
                    var hour = new Date(val +":00:00").getHours();
                    if(hour == 8 || hour ==20){
                        return true
                    }else{
                        return false
                    }
                };
            }else{
                that.echartOption.xAxis.axisLabel.interval = "auto";
            }
            that.echartObj.clear();
            that.echartObj.setOption(that.echartOption, true);
        },

        getEchartOption:function(){
            var that = this;
            return {
                title: {
                    text: '',
                    x: 'center',
                    top: 20
                },
                toolbox: {
                    feature: {
                        saveAsImage: {}
                    },
                    showTitle: false,
                    color: "#045DF8",
                    top: 20,
                    right: 30
                },
                tooltip: {
                    trigger: "axis",
                    textStyle: {
                        fontSize: 13
                    },
                    formatter: function (params) {
                        return that.setEchartShow(params);
                    },
                    padding: 8
                },
                xAxis: {
                    type: "category",
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        interval:0,
                        textStyle: { //改变刻度字体样式
                            color: function (value, index) {
                                if ($(".dateType .active").attr("name") === "10") {
                                    value = value + ":00";
                                    return that.getTimeBtDate(value, "10",index).color;
                                } else if ($(".dateType .active").attr("name") === "60") {
                                    value = value + ":00:00";
                                    return that.getTimeBtDate(value, "60",index).color;
                                }
                            },
                            fontSize: 12
                        },
                        formatter: function (value, index) {
                            if ($(".dateType .active").attr("name") === "10") {
                                value = value + ":00";
                                return that.getTimeBtDate(value, "10",index).time;
                            } else if ($(".dateType .active").attr("name") === "60") {
                                value = value + ":00:00";
                                return that.getTimeBtDate(value, "60",index).time;
                            }
                        }
                    },
                    data: []
                },
                dataZoom: [{
                    show: true,
                    realtime: true,
                    start: 50,
                    end: 100,
                    bottom: 20,
                    left:'10%',
                    right:'10%'
                },
                {
                    type: 'inside',
                    realtime: true,
                    start: 0,
                    end: 50
                }
                ],
                legend: {
                    show: true,
                    icon: "roundRect",
                    itemWidth: 20,
                    itemHeight: 10,
                    itemGap: 15,
                    top: 55,
                    right: 20,
                    data: [],
                    textStyle: {
                        color: "#333333",
                        fontSize: 14
                    }
                },
                grid: {
                    show: true,
                    bottom: "12%",
                    top: "18%",
                    containLabel: true,
                    borderWidth: 0
                },
                yAxis: [],
                series: []
            }
        },

        //填充相应的数组
        addArrNull: function (data, flag) {
            var xData = null;
            if (this.elementForecastIds[0] === "eda10m") {
                xData = { value: null, valueWd: null };
            }
            if (flag) {
                for (var i = 0; i < 96; i++) {
                    //data.push(xData);
                }
            } else {
                for (var i = 0; i < 24; i++) {
                    data = [xData].concat(data);
                }
            }
            return data;
        },

        //多请求
        multipleRequest: function (requestArr, requestParamArr, flag) {
            var that = this;
            var lon = that.stationKey.split(",")[0];
            var lat = that.stationKey.split(",")[1];
            that.stationKey = Number(lon)+","+Number(lat);
            if (requestArr.length === 1 && flag) {       //当前请求只有自动站
                $.when($.getJSON(requestArr[0], requestParamArr[0])).done(function (res) {
                    that.drawEchart(res.data, [])
                }).fail(function () {
                    that.echartObj.clear();
                })
            }

            if (requestArr.length >= 1 && !flag) {      //当前请求没有自动站，全是预报
                $.ajax(requestArr[0], {
                    data: JSON.stringify(requestParamArr[0]),
                    method: "POST",
                    contentType: "application/json",
                    dataType: "json",
                    success: function (res) {
                        that.drawEchart([], res.data[that.stationKey]);
                    }
                })
            }

            if (requestArr.length > 1 && flag) {      // 当前请求既有自动站，也有预报
                $.when($.getJSON(requestArr[0], requestParamArr[0])).done(function (res) {
                    $.ajax(requestArr[1], {
                        data: JSON.stringify(requestParamArr[1]),
                        method: "POST",
                        contentType: "application/json",
                        dataType: "json",
                        success: function (res1) {
                            
                            that.drawEchart(res.data, res1.data[that.stationKey]);
                        }
                    })
                }).fail(function () {
                    that.echartObj.clear();
                })
            }
        },

        //如果是风，节点信息为风向图标
        setSerieSymbol: function (serieObj) {
            serieObj.symbolSize = 18;
            serieObj.symbol = function (obj, param) {
                if (!param.data)
                    return "";
                var windD = param.data.valueWd;
                if ((windD !== 0 && !windD) || windD > 360)
                    return "";
                var en = WindUtil.getWindDire(WindUtil.calcWindDire(windD)).EN;
                return "image:///business/common/css/images/wind/" + en + ".png";
            }
            return serieObj;
        },
        //获取y轴对象
        getYAxisObj: function () {
            return {
                type: "value",
                axisLabel: {
                    formatter: "{value}",
                    textStyle: {
                        //改变刻度字体样式
                        color: "#333333",
                        fontSize: 12
                    }
                },
                splitNumber: 10,
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: "#333333"
                    }
                }
            };
        },
        //获取series对象
        getSerieObj: function (serieName) {
            var param = {
                name: serieName,
                data: [],
                type: "line",
                smooth: true,
                symbol: 'circle',
                symbolSize: 5,
                barWidth: 10,
                showAllSymbol: true,
                connectNulls: true,
                eleId:''
            };
            if(this.isByDateLength && $(".ybDateLengths .ybDateLengthActive").text() == "240"){
                delete param.barWidth;
            }
            return param;
        },
        //设置x轴的时间刻度
        setXAxisData: function (startTime, endTime) {
            var that = this;
            var timeArr = [];
            var interval = parseInt($(".dateType .active").attr("name"));
            var startDate = new Date(startTime).getTime();
            var endDate = new Date(endTime).getTime();
            var format = "yyyy-MM-dd hh:mm";
            if (interval === 60) {
                format = "yyyy-MM-dd hh";
            }

            if(that.isByDateLength){
                var intervalPeriod = Number($(".ybDateLengths .ybDateLengthActive").attr("interval"));
                for (var i = startDate; i <= endDate; i = i + intervalPeriod  * 60 * 60 * 1000) {
                    var time = new Date(i).format(format);
                    timeArr.push(time);
                }
            }else{
                for (var i = startDate; i <= endDate; i = i + interval * 60 * 1000) {
                    var time = new Date(i).format(format);
                    timeArr.push(time);
                }
            }

            return timeArr;
        },
        //设置echart中dataZoom的起始值
        setEchartDataZoom: function () {
            var that = this;
            if ($(".dateType .active").attr("name") === "10") {
                that.echartOption.dataZoom[0].start = 50;
                that.echartOption.dataZoom[0].end = 100;
            } else if ($(".dateType .active").attr("name") === "60") {
                that.echartOption.dataZoom[0].start = 0;
                that.echartOption.dataZoom[0].end = 100;
            }
        },
        //获取站点的名称
        getStationIdName: function () {
            var stationId = $(".sites .active").attr("name");
            var stationName = $(".sites .active").text();
            var stationLonLat = $(".sites .active").attr("lon") + "_" + $(".sites .active").attr("lat") + "_" + stationId;
            this.stationKey = $(".sites .active").attr("lon") + "," + $(".sites .active").attr("lat");
            if (!stationId && window.analysis.stationLon) {
                stationId = window.analysis.stationId;
                stationName = window.analysis.stationName;
                stationLonLat = window.analysis.stationLon + "_" + window.analysis.stationLat + "_" + window.analysis.stationId;
                this.stationKey = window.analysis.stationLon + "," + window.analysis.stationLat;
            }
            return { "stationId": stationId, "stationName": stationName, "stationLonLat": stationLonLat }
        },
        //获取echart标题
        setEchartTitle: function (stationName, startTime, endTime) {
            var that = this;
            var title = "";
            if(stationName == "" || !stationName){
                title = "经度:"+this.stationKey.split(",")[0]+" 纬度:"+this.stationKey.split(",")[1]+" ";
            }else{
                title = stationName + "站 ";
            }
            title = title + startTime.split(":")[0] + "时 至 " + endTime.split(":")[0] + "时变化趋势";
            that.echartOption.title.text = title;
        },
        //设置echart的y轴偏离grid的位置
        setYAxisPosition: function (yAxisArr) {
            var that = this;
            let offsetLeft = 0;
            let offsetRight = 0;
            if (yAxisArr.length === 1) {
                offsetLeft = 70;
                offsetRight = 70;
                that.echartOption.grid["left"] = 30;
                that.echartOption.grid["right"] = 20;
            } else if (yAxisArr.length === 2) {
                offsetLeft = 70;
                offsetRight = 70;
                that.echartOption.grid["left"] = 30;
                that.echartOption.grid["right"] = 30;
            } else if (yAxisArr.length === 3) {
                offsetLeft = 140;
                offsetRight = 70;
                that.echartOption.grid["left"] = 60;
                that.echartOption.grid["right"] = 30;
            } else if (yAxisArr.length === 4) {
                offsetLeft = 140;
                offsetRight = 140;
                that.echartOption.grid["left"] = 60;
                that.echartOption.grid["right"] = 60;
            } else if (yAxisArr.length === 5) {
                offsetLeft = 210;
                offsetRight = 140;
                that.echartOption.grid["left"] = 110;
                that.echartOption.grid["right"] = 60;
            } else if (yAxisArr.length === 6) {
                offsetLeft = 210;
                offsetRight = 210;
                that.echartOption.grid["left"] = 110;
                that.echartOption.grid["right"] = 110;
            }
            return { "offsetLeft": offsetLeft, "offsetRight": offsetRight };
        },
        //定义鼠标移到echart中弹框的内容
        setEchartShow: function (params) {
            var that = this;
            var htmlStr = "";
            var xName = params[0].name;
            htmlStr = htmlStr + xName + '<br/>';
            var unit = "";
            for (var i = 0; i < params.length; i++) {
                var seriesName = params[i].seriesName;
                var color = params[i].color;
                var value = params[i].value;
                var wdValue = "";
                if (seriesName.indexOf("10m风") > -1) {
                    value = params[i].data.value;
                    wdValue = params[i].data.valueWd; // 定义风向
                    if (value === "null" || typeof value === "undefined" || value === null) {
                        value = "-"
                    } else {
                        value = Number(value).toFixed(1);
                        wdValue = WindUtil.getWindDire(WindUtil.calcWindDire(wdValue)).CH;
                        value = wdValue + " " + value;
                    }
                }else{
                    if (value === "null" || typeof value === "undefined") {
                        value = "-";
                    }else{
                        value = Number(value).toFixed(1);
                    }
                }
                
                htmlStr = htmlStr + '<div style="display: flex;align-items: center"><div style="background-color: ' + color + ';height: 10px;width: 10px;border-radius: 50%;margin-right: 6px"></div>';
                if (that.currentModel === "单要素") {
                    var elementName = $(".elements .active").text();
                    unit = that.getUnitbyElement(elementName);
                    htmlStr = htmlStr + seriesName + "(" + elementName + ")" + '：' + value + unit + "<br/></div>";
                } else if (that.currentModel === "多要素") {
                    unit = that.getUnitbyElement(seriesName);
                    htmlStr = htmlStr + seriesName + '：' + value + unit + "<br/></div>";
                }
            }
            return htmlStr;
        },
        //根据要素，获取单位，如果单元素，只需要，获取一个元素的单位，如果多元素，需要循环获取
        getUnitbyElement: function (name) {
            var unit = "";
            if ($(".modelTabs .modelTabActive").text() === "单要素") {
                name = $(".elements .active").text();
            }
            switch (name) {
                case "2m温度":
                case "850hpa温度":
                    unit = "℃";
                    break;
                case "降水量":
                    unit = "mm";
                    break;
                case "相对湿度":
                case "700hpa湿度":
                case "850hpa湿度":
                    unit = "%";
                    break;
                case "10m风":
                case "6h阵风":
                    unit = "m/s";
                    break;
                case "海平面气压":
                    unit = "hPa";
                    break;
                case "总云量":
                    unit = "%";
                    break;
                case "能见度":
                    unit = "m";
                    break;
            }
            return unit
        },
        //获取最大值
        getMaxInArr: function (arr) {
            //arr = arr.filter(val => val > 0);
            return Math.max.apply(null, arr) + 1;
        },
        //获取最小值
        getMinInArr: function (arr) {
            //arr = arr.filter(val => val > 0);
            var min = Math.min.apply(null, arr);
            if (min !== 0) {
                min = min - 1;
            }
            return min;
        },

        //获取时间，根据时间类型，获取时，分，秒
        getTimeBtDate: function (dateStr, flag, index) {
            var mounth = new Date(dateStr).getMonth() + 1;
            var day = new Date(dateStr).getDate();
            var hour = new Date(dateStr).getHours();
            var minutes = new Date(dateStr).getMinutes();
            day = day > 9 ? day + "" : "0" + day;
            hour = hour > 9 ? hour + "" : "0" + hour;
            minutes = minutes > 9 ? minutes + "" : "0" + minutes;
            mounth = mounth > 9 ? mounth + "" : "0" + mounth;
            var returnObj = { "time": "", "color": "#333333" };
            if (flag === "10") {
                if (hour + minutes === "0000" || index == 0) {
                    returnObj.color = "#FEA444";
                    returnObj.time = hour + ":" + minutes + "\n" + day;
                } else {
                    returnObj.time = hour + ":" + minutes
                }
            } else if (flag === "60") {
                if(index == 0  || (this.isByDateLength && (hour == "08" || hour == "20"))){
                    returnObj.color = "#FEA444";
                    returnObj.time = day + "/" + hour; 
                }else{      
                    var xAxisArr = this.echartOption.xAxis.data;
                    var perTime = xAxisArr[index-1]+":00:00";
                    var currTime = xAxisArr[index]+":00:00";
                    if(new Date(perTime).getDate() != new Date(currTime).getDate()){
                        returnObj.color = "#FEA444";
                        returnObj.time = day + "/" + hour;
                    }else{
                        returnObj.time = hour;
                    }
                }
            }
            return returnObj;
        },
        //判断是否能多选或者单选,此时需判断单要素还是多要素
        checkIsSelectMore: function (obj, flag) {
            var that = this;
            if (that.currentModel === "单要素") {
                if (flag === "dataSource") {
                    if (obj.hasClass("active")) {
                        obj.removeClass("active");
                    } else {
                        obj.addClass("active");
                    }
                } else if (flag === "elements") {
                    if (!obj.hasClass("active")) {
                        obj.addClass("active").siblings().removeClass("active");
                    }
                }
            } else if (that.currentModel === "多要素") {
                if (flag === "dataSource") {
                    if (!obj.hasClass("active")) {
                        obj.addClass("active").siblings().removeClass("active");
                    }
                } else if (flag === "elements") {
                    if (obj.hasClass("active")) {
                        obj.removeClass("active");
                    } else {
                        if ($(".elements .active").length < 6) {
                            obj.addClass("active");
                        } else {
                            return false;
                        }
                    }
                }
            }
            that.getData(false);
        }
    };
    if (typeof call === 'function') {
        CafeJS.dateAnalysis = main;
        call(main);
    }

})(function (main) {
    CafeJS.models(['datepicker', 'legentconfig','timeLine3'], function () {
        main.init();
    });
});
